<template lang="html">
  <div class="editor">
    <div ref="toolbar" class="toolbar">
    </div>
    <div ref="editor" class="texts">
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'
import {imgURL, upfileApi, upfileURL} from '@/api'
import axios from 'axios'
import {getToken} from "@/utils/auth";
export default {
  name: 'editoritem',
  data() {
    return {
      // uploadPath,
      editor: null,
      info_: null,
      baseUrl: imgURL,
      uploadImgUrl: upfileURL + "/api/file/upload", // 上传的图片服务器地址
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    isClear: {
      type: Boolean,
      default: false
    },
    disabled:{
      type: Boolean,
      default: false
    },
  },
  watch: {
    isClear(val) {
      // 触发清除文本域内容
      if (val) {
        this.editor.txt.clear()
        this.info_ = null
      }
    },
    value: function(value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value)
      }
    }
    //value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
  },
  mounted() {
    this.seteditor()
    this.editor.txt.html(this.value)
  },
  methods: {
    seteditor() {
      // http://192.168.2.125:8080/admin/storage/create
      this.editor = new E(this.$refs.toolbar, this.$refs.editor)
      this.editor.config.uploadImgShowBase64 = false // base 64 存储图片
      // this.editor.config.uploadImgServer = fileURL// 配置服务器端地址
      // this.editor.config.uploadImgHeaders = { }// 自定义 header
      // this.editor.config.uploadFileName = 'file' // 后端接受上传文件的参数名
      this.editor.config.uploadImgMaxSize = 100 * 1024 * 1024 // 将图片大小限制为 10M
      this.editor.config.uploadImgMaxLength = 6 // 限制一次最多上传 3 张图片
      this.editor.config.uploadImgTimeout = 3 * 60 * 1000 // 设置超时时间

      // 配置菜单
      this.editor.config.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        // 'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        // 'emoticon', // 表情
        'image', // 插入图片
        'table', // 表格
        // 'video', // 插入视频
        // 'code', // 插入代码
        'undo', // 撤销
        'redo', // 重复
        'fullscreen' // 全屏
      ]
      //图片
      this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
        let data = resultFiles[0]
        this.upload(data,insertImgFn)

      }
      //视频
      this.editor.config.customUploadVideo = (resultFiles, insertVideoFn) => {
        let data = resultFiles[0]
        this.upload(data,insertVideoFn)
      }
      this.editor.config.onchange = (html) => {
        this.info_ = html // 绑定当前逐渐地值
        this.$emit('change', this.info_) // 将内容同步到父组件中
      }
      // 创建富文本编辑器
      this.editor.create()
    },
    upload(data,fn){
      axios({
        method: 'post',
        url: this.uploadImgUrl,
        data:{file:data},
        transformRequest: [
          (data)=> {
            // 将请求数据转换成功 formdata 接收格式
            return this.stringify(data)
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization':'Bearer '+getToken(),
        }
      }).then(res => {
        console.log(res)
        if (res.data.code==10000){
          this.URL=res.data.data.url
          console.log('URL',this.URL)

          fn(this.URL)
        }
      })
    },
    stringify(data) {
      const formData = new FormData()
      for (const key in data) {
        // eslint-disable-next-line no-prototype-builtins
        if (data.hasOwnProperty(key)) {
          if (data[key]) {
            if (data[key].constructor === Array) {
              if (data[key][0]) {
                if (data[key][0].constructor === Object) {
                  formData.append(key, JSON.stringify(data[key]))
                } else {
                  data[key].forEach((item, index) => {
                    formData.append(key + `[${index}]`, item)
                  })
                }
              } else {
                formData.append(key + '[]', '')
              }
            } else if (data[key].constructor === Object) {
              formData.append(key, JSON.stringify(data[key]))
            } else {
              formData.append(key, data[key])
            }
          } else {
            if (data[key] === 0) {
              formData.append(key, 0)
            } else {
              formData.append(key, '')
            }
          }
        }
      }
      return formData
    }
  }
}
</script>

<style lang="css" scoped>
.editor {
  width: 100%;
  margin: 0 auto;
  position: relative;
  z-index: 0;
}
.toolbar {
  border: 1px solid #ccc;
}
.texts {
  border: 1px solid #ccc;
  min-height: 150px;
}
</style>
